package com.fudan.backend.dao;

import com.fudan.backend.handler.IdTypeHandler;
import com.fudan.backend.handler.ListTypeHandler;
import com.fudan.backend.pojo.Activity;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface ActivityDao {
    @Results(id = "activityMap", value = {
            @Result(column = "activity_id", property = "activityId", typeHandler = IdTypeHandler.class),
            @Result(column = "activity_name", property = "activityName"),
            @Result(column = "start_time", property = "startTime"),
            @Result(column = "end_time", property = "endTime"),
            @Result(column = "category_id_list", property = "categoryIdList", typeHandler = ListTypeHandler.class),
            @Result(column = "fund", property = "fund"),
            @Result(column = "reach", property = "reach"),
            @Result(column = "reduce", property = "reduce"),
            @Result(column = "balance", property = "balance"),
            @Result(column = "registered_capital", property = "registeredCapital"),
            @Result(column = "monthly_sales_volume", property = "monthlySalesVolume"),
            @Result(column = "monthly_sales_value", property = "monthlySalesValue"),
            @Result(column = "status", property = "status"),
    })
    @Select("select * from t_activity")
    List<Activity> selectAllActivity();

    @ResultMap("activityMap")
    @Select("select * from t_activity where status = 1")
    List<Activity> selectAllOngoingActivity();

    @ResultMap("activityMap")
    @Select("select * from t_activity where activity_id = #{activityId, typeHandler=com.fudan.backend.handler.IdTypeHandler}")
    Activity selectActivityByActivityId(String activityId);

    @Insert("insert into t_activity values " +
            "(#{activityId, typeHandler=com.fudan.backend.handler.IdTypeHandler}, " +
            "#{activityName}, #{startTime}, " +
            "#{endTime}, #{categoryIdList, typeHandler=com.fudan.backend.handler.ListTypeHandler}, " +
            "#{fund}, #{reach}, #{reduce}, " +
            "#{balance}, #{registeredCapital}, #{monthlySalesVolume}, #{monthlySalesValue}, #{status})")
    int insertActivity(Activity activity);

    /**
     * 将余额不足的活动取消，(账户余额小于满减额)
     */
    @Update("update t_activity as ta set " +
            "ta.status = 0 " +
            "where ta.balance - ta.reduce < 0 " +
            "and ta.status = 1")
    int cancelInsufficientBalanceActivity();


    /**
     * 更新活动余额
     */
    @Update("update t_activity set balance = #{balance} " +
            "where activity_id = #{activityId} ")
    int updateActivityBalance(String activityId, Double balance);
}
